package com.iqilu.ksd.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.MaterialDialog;
import com.iqilu.ksd.MyApplication;
import com.iqilu.ksd.R;
import com.iqilu.ksd.adapter.NavigationAdapter;
import com.iqilu.ksd.bean.BoxBean;
import com.iqilu.ksd.bean.CityItemBean;
import com.iqilu.ksd.bean.ColumnItemBean;
import com.iqilu.ksd.bean.LanuchAdBean;
import com.iqilu.ksd.bean.UnreadMsgBean;
import com.iqilu.ksd.bean.UserBean;
import com.iqilu.ksd.constant.Api;
import com.iqilu.ksd.constant.Config;
import com.iqilu.ksd.constant.LanuchAd;
import com.iqilu.ksd.constant.UserInfo;
import com.iqilu.ksd.event.ChangeUserInfoEvent;
import com.iqilu.ksd.event.CityChangeEvent;
import com.iqilu.ksd.event.FragmentChangeEvent;
import com.iqilu.ksd.event.NetworkStateEvent;
import com.iqilu.ksd.event.UnreadMsgEvent;
import com.iqilu.ksd.fragment.LiveFragment;
import com.iqilu.ksd.fragment.NewsFragment;
import com.iqilu.ksd.fragment.PaikeFragment;
import com.iqilu.ksd.fragment.RadioFragment;
import com.iqilu.ksd.fragment.TVFragment;
import com.iqilu.ksd.utils.BaseUtils;
import com.iqilu.ksd.utils.CacheUtils;
import com.iqilu.ksd.utils.CityUtils;
import com.iqilu.ksd.utils.ColumnUtils;
import com.iqilu.ksd.utils.FileUtils;
import com.iqilu.ksd.utils.JSONUtils;
import com.iqilu.ksd.utils.NetworkUtils;
import com.iqilu.ksd.utils.SPUtils;
import com.iqilu.ksd.utils.UpdateUtils;
import com.jaeger.library.StatusBarUtil;
import com.jude.swipbackhelper.SwipeBackHelper;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by Coofee on 2016/9/20.
 */
public class MainActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks {

    private static String TAG = "MainActivity";

    private UserBean user;
    private long mExitTime;
    private MyApplication application;
    private NavigationAdapter navigationAdapter;
    private ArrayList<ColumnItemBean> columnList;

    private FragmentManager fragmentManager;
    private FragmentTransaction transaction;

    private NewsFragment newsFragment;
    private TVFragment tvFragment;
    private LiveFragment liveFragment;
    private PaikeFragment paikeFragment;
    private RadioFragment radioFragment;

    private View line;
    private DrawerLayout layDrawer;
    private LinearLayout layLeftMenu;
    private ImageView btSearch;
    private ListView lvMenu;
    private RadioGroup rgBottom;
    private static final int PER_LOCATION = 1001;
    private static final int PER_ALL = 1002;
    private AMapLocationClient locationClient = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        application = (MyApplication) getApplication();
        application.setMainStarted(true);
        user = ((MyApplication) getApplication()).getUser();
        SwipeBackHelper.getCurrentPage(this).setSwipeBackEnable(false);
        layDrawer = getView(R.id.lay_drawer);
        layLeftMenu = getView(R.id.lay_left_menu);
        line = getView(R.id.line);
        initNavigation();
//        StatusBarUtil.setColorForDrawerLayout(this, layDrawer, ContextCompat.getColor(this, R.color.blue_dark), Config.STATUSBAR_ALPHA);
        if (Build.VERSION.SDK_INT >= 21) {
            StatusBarUtil.setColor(this, ContextCompat.getColor(this, R.color.blue_dark), Config.STATUSBAR_ALPHA);
        }
        fragmentManager = getSupportFragmentManager();
        rgBottom = getView(R.id.rg_bottom);
        rgBottom.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                transaction = fragmentManager.beginTransaction();
                hideFragments(transaction);
                switch (checkedId) {
                    case R.id.radio_news:
                        if (newsFragment == null) {
                            newsFragment = new NewsFragment();
                            transaction.add(R.id.lay_content, newsFragment, "newsFragment");
                        } else {
                            transaction.show(newsFragment);
                        }
                        layDrawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
                        break;
                    case R.id.radio_tv:
                        if (tvFragment == null) {
                            tvFragment = new TVFragment();
                            transaction.add(R.id.lay_content, tvFragment, "tvFragment");
                        } else {
                            transaction.show(tvFragment);
                        }
                        layDrawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
                        break;
                    case R.id.radio_live:
                        if (liveFragment == null) {
                            liveFragment = new LiveFragment();
                            transaction.add(R.id.lay_content, liveFragment, "liveFragment");
                        } else {
                            transaction.show(liveFragment);
                        }
                        layDrawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
                        break;
                    case R.id.radio_paike:
                        if (paikeFragment == null) {
                            paikeFragment = new PaikeFragment();
                            transaction.add(R.id.lay_content, paikeFragment, "paikeFragment");
                        } else {
                            transaction.show(paikeFragment);
                        }
                        layDrawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
                        break;
                    case R.id.radio_me:
                        if (radioFragment == null) {
                            radioFragment = new RadioFragment();
                            transaction.add(R.id.lay_content, radioFragment, "meFragment");
                        } else {
                            transaction.show(radioFragment);
                        }
                        layDrawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
                        break;
                    default:
                        layDrawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
                        break;
                }
                transaction.commitAllowingStateLoss();
                EventBus.getDefault().post(new FragmentChangeEvent(checkedId));
            }
        });
        rgBottom.check(R.id.radio_news);
        if (user == null || user.getId() < 1) {
            hashLogin();
        } else {
            EventBus.getDefault().post(new ChangeUserInfoEvent());
        }
//        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1 && SPUtils.getPref(this, Config.IS_FIRST, true)) {
//            SPUtils.setPref(this, Config.IS_FIRST, false);
//            showPermissionsDialog();
//        }
        if (System.currentTimeMillis() / 1000 - SPUtils.getPrefLong(this, Config.CHECK_VERSION_TIME, 0) > 28800) { //间隔8小时
            new UpdateUtils(this).checkUpdate(BaseUtils.getVersion(this));
        }
        startLocation();
        getUnreadMessage();
        checkLanuchAD();
//        getBox();
    }

    private void hideFragments(FragmentTransaction transaction) {
        if (newsFragment != null) {
            transaction.hide(newsFragment);
        }
        if (tvFragment != null) {
            transaction.hide(tvFragment);
        }
        if (liveFragment != null) {
            transaction.hide(liveFragment);
        }
        if (paikeFragment != null) {
            transaction.hide(paikeFragment);
        }
        if (radioFragment != null) {
            transaction.hide(radioFragment);
        }

    }

    public void openDrawer() {
        layDrawer.openDrawer(Gravity.LEFT);
    }

    private void initNavigation() {
        btSearch = getView(R.id.bt_search);
        btSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, SearchActivity.class));
                layDrawer.closeDrawer(layLeftMenu);
            }
        });
        lvMenu = getView(R.id.lv_menu);
        columnList = ColumnUtils.getColumnList();
        navigationAdapter = new NavigationAdapter(this, columnList);
        lvMenu.setAdapter(navigationAdapter);
        lvMenu.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                newsFragment.setCurrentItem(position);
                layDrawer.closeDrawer(layLeftMenu);
            }
        });
    }

    //获取触电投票报名链接
//    private void getBox() {
//        OkHttpUtils.get().url(Api.URL_TOUPIAO_BAOMING).tag(this).build().execute(new StringCallback() {
//            @Override
//            public void onError(Call call, Exception e, int id) {
//
//            }
//
//            @Override
//            public void onResponse(String response, int id) {
//                BoxBean data = null;
//                data = JSONUtils.requestDetail(response, "data", BoxBean.class);
//                if (data != null) {
//                    SPUtils.setPref(MainActivity.this, Config.BOX_URL_BAOMING, "" + data.getToupiao());
//                    SPUtils.setPref(MainActivity.this, Config.BOX_URL_TOUPIAO, "" + data.getBaoming());
//                }
//            }
//        });
//    }

    //下载启动广告
    private void checkLanuchAD() {
        OkHttpUtils.get().url(Api.URL_ADS_LAUNCH).tag(this).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                final LanuchAdBean ADData;
                String startAdMd5 = SPUtils.getPref(MainActivity.this, LanuchAd.MD5, "");
                ADData = JSONUtils.requestDetail(response, "data", LanuchAdBean.class);
                String extName = ".jpg";
                if(ADData != null && ADData.getImg().toLowerCase().endsWith("gif")){
                    extName = ".gif";
                }
                if (ADData != null && !ADData.getMd5().equals(startAdMd5) || !FileUtils.isFileExists(CacheUtils.getCacheDir(MainActivity.this) + startAdMd5 + extName)) {
                    downLoadLanuchAd(ADData);
                }
            }
        });
    }

    //是否有未读消息
    private void getUnreadMessage() {
        String url = Api.URL_MSG_HASUNREAD;
        OkHttpUtils.get().url(url).tag(this).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                int count = 0;
                UnreadMsgBean result = null;
                result = JSONUtils.requestDetail(response, "data", UnreadMsgBean.class);
                if (result != null) {
                    count = result.getHas();
                }
                SPUtils.setPref(MainActivity.this, UserInfo.MSGCOUNT, count);
                if (count > 0) {
                    EventBus.getDefault().post(new UnreadMsgEvent(count));
                }
            }
        });
    }

    private void downLoadLanuchAd(final LanuchAdBean ADData) {
        if (ADData == null || ADData.getImg() == null) return;
        String path = CacheUtils.getCacheDir(this);
        String extName = ".jpg";
        if(ADData.getImg().toLowerCase().endsWith("gif")){
            extName = ".gif";
        }
        String name = "" + ADData.getMd5() + extName;
        Log.i(TAG, "path=" + path);
        OkHttpUtils.get().url(ADData.getImg()).tag(this).build().execute(new FileCallBack(path, name) {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(File response, int id) {
                SPUtils.setPref(MainActivity.this, LanuchAd.MD5, ADData.getMd5());
                SPUtils.setPref(MainActivity.this, LanuchAd.URL, ADData.getUrl());
                SPUtils.setPref(MainActivity.this, LanuchAd.IMG, ADData.getImg());
                SPUtils.setPref(MainActivity.this, LanuchAd.TITLE, ADData.getTitle());
                SPUtils.setPref(MainActivity.this, LanuchAd.SHARE_ICON, ADData.getShareicon());
            }
        });
    }

    @AfterPermissionGranted(PER_LOCATION)
    private void startLocation() {
        String perm = Manifest.permission.ACCESS_FINE_LOCATION;
        if (EasyPermissions.hasPermissions(this, perm)) {
            initLocation();
            locationClient.startLocation();
        } else {
            EasyPermissions.requestPermissions(this, getString(R.string.per_con_location), PER_LOCATION, perm);
        }
    }

    private void showPermissionsDialog() {
        final MaterialDialog dialog = new MaterialDialog(this);
        dialog.content(getString(R.string.per_description))
                .btnText(getString(R.string.cancel), getString(R.string.ensure))
                .show();
        dialog.setOnBtnClickL(
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        dialog.dismiss();
                    }
                },
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        requestPermissions();
                        dialog.dismiss();
                    }
                }
        );
    }

    private void requestPermissions() {
        String perms[] = {
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.CAMERA
        };
        EasyPermissions.requestPermissions(this, getString(R.string.per_description), PER_ALL, perms);
    }

    private void initLocation() {
        //初始化client
        locationClient = new AMapLocationClient(this.getApplicationContext());
        //设置定位参数
        locationClient.setLocationOption(getDefaultOption());
        // 设置定位监听
        locationClient.setLocationListener(locationListener);
    }

    private AMapLocationClientOption getDefaultOption() {
        AMapLocationClientOption mOption = new AMapLocationClientOption();
        mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
        mOption.setHttpTimeOut(30000);
        mOption.setNeedAddress(true);
        mOption.setOnceLocation(true);//可选，设置是否单次定位。默认是false
        mOption.setOnceLocationLatest(false);
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);
        return mOption;
    }

    AMapLocationListener locationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation loc) {
            if (null != loc && loc.getErrorCode() == 0) {
                //解析定位结果
                String city = loc.getCity();
                stopLocation();
                Log.i(TAG, "city=" + city);
                CityItemBean item = CityUtils.getCity(city);
                if (item.getCityId() == SPUtils.getPref(MainActivity.this, Config.CITY_ID, 0)) {
                    return;
                }
                SPUtils.setPref(MainActivity.this, Config.CITY, item.getCityName());
                SPUtils.setPref(MainActivity.this, Config.CITY_ID, item.getCityId());
                EventBus.getDefault().post(new CityChangeEvent());
            }
        }
    };

    private void stopLocation() {
        locationClient.stopLocation();
    }

    private void destroyLocation() {
        if (null != locationClient) {
            locationClient.onDestroy();
            locationClient = null;
        }
    }

    public void toggleHide(int status) {
        rgBottom.setVisibility(status);
        line.setVisibility(status);
    }

    // 网络状态发生改变
    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onMessageEvent(NetworkStateEvent event) {
        user = ((MyApplication) getApplication()).getUser();
        if (NetworkUtils.isAvailable(this) && user == null) {
            hashLogin();
        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onMessageEvent(CityChangeEvent event){
        int id = SPUtils.getPref(this,Config.CITY_ID,0);
        String name = SPUtils.getPref(this,Config.CITY,getString(R.string.default_city));
        columnList.get(2).setId(id);
        columnList.get(2).setName(name);
        navigationAdapter.setData(columnList);
        navigationAdapter.notifyDataSetChanged();
    }

    // 有未读消息
    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onMessageEvent(UnreadMsgEvent event) {
//        RadioButton radioMy = (RadioButton) rgBottom.getChildAt(4);
//        Drawable drawable;
//        if (event.getCount() > 0) {
//            drawable = ContextCompat.getDrawable(this, R.drawable.bt_bottom_me_message);
//        } else {
//            drawable = ContextCompat.getDrawable(this, R.drawable.bt_bottom_radio);
//        }
//        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
//        radioMy.setCompoundDrawables(null, drawable, null, null);
    }

    /***
     * 旋转屏幕之后回调
     *
     * @param newConfig newConfig
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        /***
         * 旋转屏幕时隐藏标题栏
         */
        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().getDecorView().invalidate();
        } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            final WindowManager.LayoutParams attrs = getWindow().getAttributes();
            attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().setAttributes(attrs);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE && tvFragment != null) { // 当前是否是横屏
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                tvFragment.resetPageToPortrait();
                return true;
            }
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                Toast.makeText(this, getResources().getText(R.string.exit), Toast.LENGTH_SHORT).show();
                mExitTime = System.currentTimeMillis();
            } else {
                application.setMainStarted(false);
                finish();
            }
            return true;
        }
        if (keyCode == KeyEvent.KEYCODE_MENU) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        String tip;
        switch (requestCode) {
            case PER_LOCATION:
                tip = getString(R.string.per_con_location);
                break;
            default:
                tip = getString(R.string.per_con_location);
                break;
        }
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this, tip)
                    .setTitle(getString(R.string.per_title))
                    .setPositiveButton(getString(R.string.setting))
                    .setNegativeButton(getString(R.string.cancel), null)
                    .setRequestCode(requestCode)
                    .build()
                    .show();
        }

    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        destroyLocation();
        Log.i(TAG,"onDestroy");
    }
}
